package it.polimi.comorazio.fragments;

import it.polimi.comorazio.R;
import it.polimi.comorazio.activities.ArchitectDetailActivity;
import it.polimi.comorazio.activities.ArchitectListActivity;
import it.polimi.comorazio.data.ArchitectVo;
import it.polimi.comorazio.data.DataBaseHelper;
import it.polimi.comorazio.data.ImageVo;
import it.polimi.comorazio.data.PointOfInterestVo;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * A fragment representing a single Architect detail screen. This fragment is
 * either contained in a {@link ArchitectListActivity} in two-pane mode (on
 * tablets) or a {@link ArchitectDetailActivity} on handsets.
 */
public class ArchitectDetailFragment extends Fragment {

	/**
	 * The fragment argument representing the item ID that this fragment
	 * represents.
	 */
	public static final String ARG_ITEM_ID = "item_id";

	private ArchitectVo architect = null;
	private ImageVo image = null;
	private List<PointOfInterestVo> poiList = new ArrayList<PointOfInterestVo>();

	/**
	 * Mandatory empty constructor for the fragment manager to instantiate the
	 * fragment (e.g. upon screen orientation changes).
	 */
	public ArchitectDetailFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments().containsKey(ARG_ITEM_ID)) {
			// Load the dummy content specified by the fragment
			// arguments. In a real-world scenario, use a Loader
			// to load content from a content provider.
			// TODO Cannot use CursorLoader because the component in charge of
			// updating the view must be an adapter and those only work on
			// ListView, GridView or Spinner
			DataBaseHelper dbHelper = new DataBaseHelper(getActivity());
			dbHelper.createDataBase();
			dbHelper.openDataBase();
			Cursor c = dbHelper.getArchitectById(Integer
					.parseInt(getArguments().getString(ARG_ITEM_ID)));
			architect = new ArchitectVo(c, 0, DataBaseHelper.getCurrentLocale(getActivity()));
			c.close();
			c = dbHelper.getImagesOfArchitectById(Integer
					.parseInt(getArguments().getString(ARG_ITEM_ID)));
			image = new ImageVo(c, 0);
			c.close();
			c = dbHelper.getPointsOfInterestByArchitectId(Integer
					.parseInt(getArguments().getString(ARG_ITEM_ID)));
			c.moveToFirst();
			while (!c.isAfterLast()) {
				PointOfInterestVo poi = new PointOfInterestVo(c,
						c.getPosition(), DataBaseHelper.getCurrentLocale(getActivity()));
				Cursor c1 = dbHelper
						.getImagesOfPointOfInterestById(poi.getId());
				c1.moveToFirst();
				while (!c1.isAfterLast()) {
					poi.setImage(new ImageVo(c1, c1.getPosition()));
					poiList.add(poi);
					c1.moveToNext();
					break;
				}
				c1.close();
				c.moveToNext();
			}
			c.close();
			dbHelper.close();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View rootView = inflater.inflate(
				R.layout.fragment_architect_detail, container, false);

		if (architect != null && image != null && !poiList.isEmpty()) {
			getActivity().setTitle("> " + architect.getName());
			((TextView) rootView.findViewById(R.id.architectName)).setText("> "
					+ architect.getName());
			((TextView) rootView.findViewById(R.id.architect_biography))
					.setText(architect.getBiography());
			((TextView) rootView.findViewById(R.id.architectBornDate))
					.setText(architect.getBorn());
			((TextView) rootView.findViewById(R.id.architectDiedDate))
					.setText(architect.getDied());
			((TextView) rootView.findViewById(R.id.architectMoreInfoLink))
					.setText(architect.getMoreInfoLink());

			int resourceId = image.getImageIdentifier(this.getActivity()
					.getResources());

			Drawable architectImage = this.getActivity().getResources()
					.getDrawable(resourceId);

			((ImageView) rootView.findViewById(R.id.architectImage))
					.setImageDrawable(architectImage);

			// Instantiate a ViewPager and a PagerAdapter
			final ViewPager mPager = (ViewPager) rootView
					.findViewById(R.id.pager);

			mPager.setAdapter(new FragmentPagerAdapter(getActivity()
					.getSupportFragmentManager()) {

				@Override
				public int getCount() {
					return poiList.size();
				}

				@Override
				public Fragment getItem(int position) {
					Bundle arguments = new Bundle();
					arguments.putString(ImageFragment.ARG_POSITION,
							String.valueOf(poiList.get(position).getId()));
					arguments.putInt(
							ImageFragment.ARG_RESOURCE_ID,
							poiList.get(position)
									.getImage()
									.getImageIdentifier(
											getActivity().getResources()));

					ImageFragment fragment = new ImageFragment();
					fragment.setArguments(arguments);

					return fragment;
				}
			});

			OnPageChangeListener changer = new OnPageChangeListener() {

				@Override
				public void onPageSelected(int pos) {
					((TextView) rootView.findViewById(R.id.poi_name))
							.setText(poiList.get(pos).getName());
					if (pos == 0) {
						((Button) rootView.findViewById(R.id.prev_image))
								.setVisibility(View.INVISIBLE);
					} else {
						((Button) rootView.findViewById(R.id.prev_image))
								.setVisibility(View.VISIBLE);
					}
					if (pos == poiList.size() - 1) {
						((Button) rootView.findViewById(R.id.next_image))
								.setVisibility(View.INVISIBLE);
					} else {
						((Button) rootView.findViewById(R.id.next_image))
								.setVisibility(View.VISIBLE);
					}
				}

				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {
				}

				@Override
				public void onPageScrollStateChanged(int arg0) {
				}
			};

			mPager.setOnPageChangeListener(changer);

			changer.onPageSelected(0);

			((Button) rootView.findViewById(R.id.prev_image))
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							mPager.setCurrentItem(mPager.getCurrentItem() - 1,
									true);
						}
					});

			((Button) rootView.findViewById(R.id.next_image))
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							mPager.setCurrentItem(mPager.getCurrentItem() + 1,
									true);
						}
					});

		}

		return rootView;
	}

}
